package com.excilys.capicsoubank.services.impl;

import org.hibernate.Hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.excilys.capicsoubank.dao.UserDao;
import com.excilys.capicsoubank.entities.User;

/**
 * Service pour charger l'utilisateur à la connexion.
 * 
 * @author Nicolas Poirier
 */
@Service("userDetailsService")
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserDao userDao;

	private static final Logger LOG = LoggerFactory
			.getLogger(UserDetailsServiceImpl.class);

	@Override
	public UserDetails loadUserByUsername(String username) {

		LOG.debug(username);
		User user = userDao.getUserByUsername(username);

		if (user == null)
			throw new UsernameNotFoundException(username);

		Hibernate.initialize(user.getAuthorities());
		return user;
	}
}
